/**
 * 
 */
package com.pactera.android.version;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;

import com.pactera.android.model.VersionInfo;

/**
 * @author David Zheng
 *
 */
public class DownloadManager {
	
	static final String TAG = "DownloadManager";
	
	private static final String savePath = "/sdcard/updatePactera/";
	
	private static final String saveFileName = savePath + "newPactera.apk";
	
	private Context context;
	
	/**
	 * Gets the new version info from the Server 
	 * 
	 * @param is
	 * @return
	 * @throws Exception
	 */
	public VersionInfo getUpdataInfo(InputStream is) throws Exception {
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(is, "utf-8");
		int type = parser.getEventType();
		VersionInfo info = new VersionInfo();
		while (type != XmlPullParser.END_DOCUMENT) {
			switch (type) {
			case XmlPullParser.START_TAG:
				if ("version".equals(parser.getName())) {
					info.setVersion(parser.nextText());
				} else if ("url".equals(parser.getName())) {
					info.setUrl(parser.nextText());
				} else if ("description".equals(parser.getName())) {
					info.setDescription(parser.nextText());
				} else if ("mandatory".equals(parser.getName())) {
					info.setMandatoryUpdate(Boolean.valueOf(parser.nextText()));
				}
				break;
			}
			type = parser.next();
		}
		return info;
	}
	
	
	/**
	 * download the file from server 
	 * 
	 * @param path the server address
	 * @param pd
	 * @return
	 * @throws IOException 
	 * @throws Exception
	 */
	public File getFileFromServer(String path, ProgressDialog pd) throws IOException {
		//check if the external storage is available.			
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
			URL url = new URL(path);
			HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);			 
			pd.setMax(conn.getContentLength());// set the progress bar size						
			File file = new File(savePath);			
			if(!file.exists()){  
                file.mkdir();          
            }  
					
			File apkFile = new File(saveFileName);
			FileOutputStream fos = new FileOutputStream(apkFile);					
			InputStream is = conn.getInputStream();			
			BufferedInputStream bis = new BufferedInputStream(is);
		
			byte[] buffer = new byte[1024];
			int len ;
			int total=0;
			while((len =bis.read(buffer))!=-1){
				fos.write(buffer, 0, len);
				total+= len;				
				pd.setProgress(total);
			}
			fos.close();
			bis.close();
			is.close();
			
			return apkFile;
		}
		else{
			return null;
		}				
	}


	/**
	 * @return the context
	 */
	public Context getContext() {
		return context;
	}


	/**
	 * @param context the context to set
	 */
	public void setContext(Context context) {
		this.context = context;
	}
	
	

}
